<template>
  <BaseLayout>
    <template #content>
      <div v-if="userState.getUserRoles?.includes(role.customer_service)">
        <el-table
          :data="tableData"
          border
          fit
          style="width: 100%"
        >
          <el-table-column
            prop="id"
            label="举报编号"
            align="center"
            show-overflow-tooltip
          />

          <el-table-column
            prop="reportType"
            label="举报类型"
            align="center"
            :formatter="formatType"
            show-overflow-tooltip
          />

          <el-table-column
            prop="reason"
            label="举报原因"
            align="center"
            show-overflow-tooltip
          />

          <el-table-column
            prop="createTime"
            label="举报时间"
            align="center"
            :formatter="formatTime"
            show-overflow-tooltip
          />

          <el-table-column
            label="操作"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="checkDetail(scope.row)"
              >
                审阅
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-else>
        <el-alert
          title="抱歉，您没有权限访问该页面"
          type="error"
          :closable="false"
          style="margin-bottom: 20px"
        />
      </div>

      <el-dialog
        v-model="dialogVisible"
        title="审阅举报"
        width="70%"
        @close="handleDialogClose"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        align-center
      >
        <div v-if="currentReport?.reportType == reportType.COMMENT">
          <el-form>
            <el-form-item label="举报类型">
              {{ formatType(null, null, currentReport?.reportType) }}
            </el-form-item>

            <el-form-item label="举报原因">
              {{ currentReport?.reason }}
            </el-form-item>

            <el-form-item label="评论内容">{{ commentContent }}</el-form-item>

            <el-form-item label="举报时间">
              {{ formatTime(null, null, currentReport?.createTime) }}
            </el-form-item>
          </el-form>
        </div>

        <div v-else>
          <div
            ref="playerContainer"
            class="video-player"
          />
        </div>

        <template #footer>
          <el-button
            type="primary"
            @click="handleResult(true)"
          >
            通过
          </el-button>

          <el-button
            type="warning"
            @click="handleResult(false)"
          >
            驳回
          </el-button>

          <el-button @click="handleDialogClose">取消</el-button>
        </template>
      </el-dialog>
    </template>
  </BaseLayout>
</template>

<script setup lang="ts">
import { auditReport, getAuditReportList } from '@/api/report'
import { reportStatus, reportType, role, videoStatus } from '@/utils/globalOptions'
import { useUserStoreWithOut } from '@/store/modules/user'
import dayjs from 'dayjs'
import { getDictList } from '@/api/dict'
import { saveAuditReportLog } from '@/api/reportLog'
import { ElMessage } from 'element-plus'
import { deleteComment, getCommentContent } from '@/api/comment'
import { auditVideo, getVideoDetail } from '@/api/video'
import { IPlayerOptions } from 'xgplayer/es/player'
import Player from 'xgplayer'
import 'xgplayer/dist/index.min.css'
import HlsJsPlayer from 'xgplayer-hls'

const userState = useUserStoreWithOut()

const tableData = ref<any[]>([])
const params = reactive({
  pageNo: 1,
  pageSize: 10
})
const total = ref(0)

const typeOptions = ref()

/**
 * 当前处理的举报
 */
const currentReport = ref(null)

onMounted(async () => {
  if (userState.getUserRoles?.includes(role.customer_service)) {
    await getTableData()
    typeOptions.value = await getDictList('cv_report_types')
  }
})

const getTableData = async () => {
  const res = await getAuditReportList(params)
  tableData.value = res.list
  total.value = res.total
}

const formatTime = (_row, _col, callValue) => {
  if (!callValue) {
    return ''
  }

  return callValue ? dayjs(callValue).format('YYYY-MM-DD HH:mm:ss') : '-'
}

const formatType = (_row, _col, callValue) => {
  if (!callValue || !typeOptions.value) {
    return ''
  }

  const option = typeOptions.value.find((item: any) => item.value === callValue)
  return option.label || ''
}

/**
 * 查看详情
 */
const checkDetail = (row: any) => {
  currentReport.value = row
  openDialog()
}

/**
 * 处理结果
 */
const handleResult = async (isPass: boolean) => {
  if (isPass) {
    currentReport.value.status = reportStatus.AUDIT_PASS
    if (currentReport.value.reportType === reportType.VIDEO) {
      await auditVideo({
        id: video.value.id,
        status: videoStatus.ILLEGAL
      })
    } else {
      await deleteComment(currentReport.value.childrenId)
    }
  } else {
    currentReport.value.status = reportStatus.AUDIT_FAIL
  }
  await auditReport(currentReport.value)
  await saveAuditReportLog({
    reportId: currentReport.value.id
  })
  await getTableData()
  ElMessage.success('操作成功')
  handleDialogClose()
}

const dialogVisible = ref(false)
const commentContent = ref('')

/**
 * 视频播放器
 */
const playerContainer = ref(null)
let player = null
const video = ref(null)

const openDialog = async () => {
  if (currentReport.value) {
    if (currentReport.value.reportType === reportType.COMMENT) {
      commentContent.value = await getCommentContent(currentReport.value.childrenId)
      dialogVisible.value = true
    } else {
      video.value = await getVideoDetail(currentReport.value.childrenId)
      dialogVisible.value = true

      nextTick(() => {
        if (playerContainer.value && video.value?.resource720p && video.value?.resource1080p) {
          player = new Player(<IPlayerOptions>{
            el: playerContainer.value,
            url: video.value.resource720p,
            controls: true,
            fluid: true,
            lang: 'zh-cn',
            volume: 0.6,
            pip: true,
            autoplay: false,
            plugins: [HlsJsPlayer]
          })

          player.emit('resourceReady', [
            {
              url: video.value?.resource720p,
              definition: '高清 720p'
            },
            {
              url: video.value?.resource1080p,
              definition: '超清 1080p'
            }
          ])

          if (video.value?.thumbnailUrl) {
            player.poster = video.value?.thumbnailUrl
          }
        }
      })
    }
  }
}

const handleDialogClose = () => {
  currentReport.value = null
  commentContent.value = ''
  video.value = null
  player = null
  dialogVisible.value = false
}
</script>

<style scoped lang="scss">
.video-player {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
}
</style>
